<template>
  <div class="app-container" style="height: 100%">
    <div
      class="app-container-inner"
      style="display: flex; flex-direction: column"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <div class="header flex-justify-between">
        <div class="btn_group">
          <router-link to="/net/new">
            <HPlainButton> 新增服务商 </HPlainButton>
          </router-link>

          <!-- 编辑策略 -->
          <EditStrategy :network-ids="ids" @update="getnetworkListRows" />

          <el-dropdown trigger="click">
            <HButton>
              <span>更多</span>
              <el-icon style="margin-left: 5px">
                <ArrowDown />
              </el-icon>
            </HButton>

            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="onNetworkMap('add')"> 服务商地图 </el-dropdown-item>
                <el-dropdown-item @click="onNetworkMap('in')"> 导入服务商 </el-dropdown-item>
                <el-dropdown-item @click="onNetworkMap('out')"> 导出服务商 </el-dropdown-item>
                <el-dropdown-item :disabled="ids.length <= 0" @click="changeTeam"
                  >修改团队</el-dropdown-item
                >
                <el-dropdown-item :disabled="ids.length <= 0" @click="changeAll(1, '启用')">
                  批量启用
                </el-dropdown-item>
                <el-dropdown-item :disabled="ids.length <= 0" @click="changeAll(2, '禁用')">
                  批量禁用
                </el-dropdown-item>
                <el-dropdown-item :disabled="ids.length <= 0" @click="changeAll(3, '删除')">
                  批量删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="search">
          <el-select
            class="net_category"
            v-model="teamType"
            placeholder="团队模式"
            clearable
            @change="getnetworkListRows"
          >
            <el-option
              v-for="item in teamTypeList"
              :key="item.value"
              :label="item.text"
              :value="item.value"
            />
          </el-select>
          <el-select
            class="net_category"
            placeholder="服务商分类"
            filterable
            clearable
            @change="getnetworkListRows"
            v-model="networkTypeId"
            :filter-method="handleGetNetworkTypeOptions"
            remote-show-suffix
          >
            <el-option
              v-for="item in netWorktypeOptions"
              :key="item.name"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
          <!-- <el-select class="net_category" v-model="type" placeholder="服务商类型" clearable @change="getnetworkListRows">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select> -->
          <el-input
            placeholder="服务商名称/负责人/手机号/所属地址"
            @keyup.enter="getnetworkListRows"
            v-model="name"
            class="keyword"
            clearable
            @clear="getnetworkListRows"
          />
          <div class="btn_group">
            <HButton type="primary" @click="getnetworkListRows">
              <el-icon class="mr5">
                <Search />
              </el-icon>
              搜索
            </HButton>
            <HButton @click="onReset">
              <el-icon class="mr5">
                <RefreshRight />
              </el-icon>
              重置
            </HButton>
          </div>
        </div>
      </div>
      <div class="table" style="flex: 1; position: relative">
        <el-table
          :border="true"
          height="100%"
          style="position: absolute"
          stripe
          resizable
          :data="tableDataList"
          @selection-change="handleChange"
          @row-dblclick="goEdit"
        >
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
          <el-table-column type="selection" width="40" fixed />

          <!-- 序号 -->
          <el-table-column fixed type="index" label="序号" width="50" />

          <!-- 服务商名称 -->
          <el-table-column show-overflow-tooltip fixed label="服务商名称" width="120">
            <template #default="scope">
              <span class="xy_main_btn" @click="goEdit(scope.row)">{{ scope.row.name }}</span>
            </template>
          </el-table-column>

          <!-- 服务商状态 -->
          <el-table-column prop="status" label="服务商状态" width="86">
            <template #default="scope">
              <HStatus type="info" v-if="scope.row.status">禁用</HStatus>
              <HStatus v-else>启用</HStatus>
            </template>
          </el-table-column>

          <!-- 团队模式 -->
          <el-table-column prop="teamType" label="团队模式" width="80">
            <template #default="scope">
              <span>{{ scope.row.teamType == 1 ? '团队' : '个人' }}</span>
            </template>
          </el-table-column>

          <!-- 服务商分类 -->
          <el-table-column
            show-overflow-tooltip
            prop="networkType"
            label="服务商分类"
            width="120"
          />
          <!-- <el-table-column prop="type" label="服务商类型" width="90">
            <template #default="scope">
              <span>{{ scope.row.type == 1 ? '销售服务商' : scope.row.type == 2 ? '售后服务商' : '包含两者' }}</span>
            </template>
          </el-table-column> -->
          <!-- 确认结单策略 -->
          <el-table-column prop="autoSureReceiveOrder" label="确认接单策略" width="106">
            <template #default="scope">
              <span v-if="scope.row.autoSureReceiveOrder">自动确认接单</span>
              <span v-else type="success">人工确认接单</span>
            </template>
          </el-table-column>

          <!-- 全部工单 -->
          <el-table-column
            show-overflow-tooltip
            align="right"
            prop="totalOrderQty"
            label="全部工单"
            width="80"
          />

          <!-- 服务中的工单 -->
          <el-table-column
            show-overflow-tooltip
            align="right"
            prop="serviceOrderQty"
            label="服务中的工单"
            width="100"
          />

          <!-- 服务商负责人 -->
          <el-table-column
            show-overflow-tooltip
            prop="managerUserName"
            label="服务商负责人"
            width="100"
          />

          <!-- 联系电话 -->
          <el-table-column
            show-overflow-tooltip
            prop="managerUserPhone"
            label="联系电话"
            width="110"
          />

          <!-- 所属地址 -->
          <el-table-column show-overflow-tooltip label="所属地址" width="220">
            <template v-slot="item">
              {{ item.row.province }}{{ item.row.city }}{{ item.row.area
              }}{{ item.row.town }}&nbsp;{{ item.row.address }}
            </template>
          </el-table-column>

          <!-- 创建时间 -->
          <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="128" />

          <!-- 更新时间 -->
          <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="128" />
        </el-table>
      </div>
      <div class="footer">
        <Pagination
          ref="pagination"
          :list_total="total"
          @size-change="getnetworkListRows"
          @current-change="getnetworkListRows"
        />
      </div>
    </div>

    <!--服务商导出-->
    <HModal title="服务商导出" v-model="exportDialog" width="800">
      <el-space direction="vertical" alignment="start" :size="24">
        <el-space direction="vertical" alignment="start">
          <div>条件搜索</div>
          <el-space>
            <el-select
              style="width: 140px"
              v-model="category"
              @change="getnetworkListRows"
              placeholder="服务商模式"
              clearable
            >
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-select
              style="width: 140px"
              placeholder="服务商分类"
              filterable
              clearable
              @change="getnetworkListRows"
              v-model="networkTypeId2"
              :filter-method="handleGetNetworkTypeOptions"
              remote-show-suffix
            >
              <el-option
                v-for="item in netWorktypeOptions"
                :key="item.name"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
            <!-- <el-select v-model="type" placeholder="服务商类型" clearable @change="getnetworkListRows" style="width: 140px">
              <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select> -->
            <el-input
              placeholder="服务商名称/负责人/手机号/所属地址"
              @keyup.enter="getnetworkListRows"
              v-model="name"
              class="w120"
              style="width: 230px"
              clearable
            ></el-input>
          </el-space>
        </el-space>

        <!-- 导出字段 -->
        <el-space direction="vertical" alignment="start">
          <el-space>
            <div style="color: #505050">导出字段</div>
            <div style="color: #a6a6a6; font-size: 12px">（拖拽可排序）</div>
            <HLink type="error" @click="handleRemoveAllExportField">清空全部</HLink>
          </el-space>
          <el-space wrap :size="10">
            <div
              v-for="(column, index) in exportFields"
              :key="column.value"
              :draggable="true"
              @dragstart="handleDragStart(index)"
              @dragend="handleDragEnd"
              @dragenter="handleDragEnter(index)"
              @mouseenter="() => (column.showClose = true)"
              @mouseleave="() => (column.showClose = false)"
              class="export-field-item"
              @click="handleRemoveFromExportFields(column)"
            >
              <div class="export-field-item-text">{{ column.name }}</div>
              <div class="export-field-item-btn">-</div>
            </div>
          </el-space>
        </el-space>

        <!-- 系统字段 -->
        <el-space direction="vertical" alignment="start">
          <el-space>
            <div style="color: #505050">系统字段</div>
            <div style="color: #a6a6a6; font-size: 12px">（点击添加）</div>
            <HLink type="error" @click="handleAddALLToExportFields(1)">添加全部</HLink>
          </el-space>
          <el-space wrap :size="10">
            <div
              :key="column.id"
              @mouseenter="() => (column.showAdd = true)"
              @mouseleave="() => (column.showAdd = false)"
              v-for="column in sysInitExportFields"
              @click="handleAddToExportFields(column, 1)"
              class="add-field-item"
            >
              <div class="add-field-item-text">{{ column.name }}</div>
              <div class="add-field-item-btn">+</div>
            </div>
          </el-space>
        </el-space>

        <!-- 自定义字段 -->
        <el-space direction="vertical" alignment="start">
          <el-space>
            <div style="color: #505050">服务商自定义字段</div>
            <div style="color: #a6a6a6; font-size: 12px">（点击添加）</div>
            <HLink type="error" @click="handleAddALLToExportFields(2)">添加全部</HLink>
          </el-space>
          <el-space wrap :size="10">
            <div
              :key="column.id"
              v-for="column in customFields"
              @mouseenter="() => (column.showAdd = true)"
              @mouseleave="() => (column.showAdd = false)"
              class="add-field-item"
              @click="handleAddToExportFields(column, 2)"
            >
              <div class="add-field-item-text">{{ column.name }}</div>
              <div class="add-field-item-btn">+</div>
            </div>
          </el-space>
        </el-space>
      </el-space>
      <template #footerRight>
        <HButton is-modal type="success" @click="handleSaveAndExportNetworkField"
          >保存并导出</HButton
        >
        <HButton is-modal type="primary" @click="handleSaveNetworkField">保存</HButton>
        <HButton is-modal @click="exportDialog = false">取消</HButton>
      </template>
    </HModal>
    <HModal
      title="修改团队"
      v-model="teamTypeDialog"
      size="small"
      @close=";(teamTypeDialog = false), (team = 1)"
    >
      <el-radio-group v-model="team">
        <el-radio :value="1">团队</el-radio>
        <el-radio :value="2">个人</el-radio>
      </el-radio-group>
      <template #footerRight>
        <HButton type="primary" is-modal @click="saveTeam">保存</HButton>
        <HButton is-modal @click=";(teamTypeDialog = false), (team = 1)">取消 </HButton>
      </template>
    </HModal>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, watch, onMounted } from 'vue'
  import { ArrowDown, RefreshRight, Search } from '@element-plus/icons-vue'
  import { useRouter, useRoute } from 'vue-router'
  import useBatch from './useBatch'
  import { ElMessage } from 'element-plus'
  import EditStrategy from './components/EditStrategy/index.vue'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import { updateNetworkTeamType } from '../../../api/network'
  import _ from 'lodash'
  import useGetNetowrkTypeOptionsService from '../new/services/useGetNetowrkTypeOptionsService'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.network.networkList,
  })

  let {
    loading,
    changeAll,
    ids,
    getnetworkListRows,
    getNetworkExportFieldList,
    getNetworkSysInitExportFieldList,
    getNetworkCustomFieldList,
    pagination,
    total,
    category,
    networkTypeId,
    networkTypeId2,
    type,
    tableDataList,
    name,
    exportFields,
    sysInitExportFields,
    customFields,
    teamType,
    handleChange,
    handleSaveAndExportNetworkField,
    handleAddToExportFields,
    handleRemoveFromExportFields,
    handleRemoveAllExportField,
    handleSaveNetworkField,
    handleAddALLToExportFields,
  } = useBatch()
  const router = useRouter()
  const route = useRoute()
  const categoryList = ref([
    { name: '内部服务商', id: 1 },
    { name: '外部服务商', id: 2 },
    { name: '第三方服务商', id: 3 },
  ])
  const typeList = ref([
    { name: '包含两者', id: '0' },
    { name: '销售服务商', id: '1 ' },
    { name: '售后服务商', id: '2' },
  ])
  const exportDialog = ref(false)
  // 服务商编辑
  const goEdit = (n: { id: string }) => {
    router.push('/net/netdetail/' + n.id)
  }

  const onNetworkMap = async (val) => {
    switch (val) {
      case 'add':
        ElMessage.success('正在升级维护中，敬请期待...')
        break
      case 'out':
        await getNetworkExportFieldList()
        await getNetworkSysInitExportFieldList()
        await getNetworkCustomFieldList()
        exportFields.value.forEach((column) => {
          if (column.type === 1) {
            const index = sysInitExportFields.value.findIndex((item) => item.code === column.value)
            sysInitExportFields.value.splice(index, 1)
          } else if (column.type === 2) {
            const index = customFields.value.findIndex((item) => item.id === column.value)
            customFields.value.splice(index, 1)
          }
        })

        exportDialog.value = true
        break
      case 'in':
        router.push('/net/networkImport')
        break
    }
  }
  const teamTypeList = ref([
    { text: '团队', value: 1 },

    { text: '个人', value: 2 },
  ])
  const team = ref(1)
  const teamTypeDialog = ref(false)
  const changeTeam = () => {
    teamTypeDialog.value = true
  }
  // 保存团队修改
  const saveTeam = () => {
    updateNetworkTeamType(ids.value, team.value).then((res) => {
      if (res.data.code == 20000) {
        teamTypeDialog.value = false
        ids.value = []
        getnetworkListRows()
      }
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
        })
    })
  }

  // 拖拽的元素的索引
  const moveIndex = ref(-1)

  // 目标位置
  const targetIndex = ref(-1)

  // 拖拽开始事件
  const handleDragStart = (index: number) => {
    moveIndex.value = index
  }

  // 拖拽结束事件
  const handleDragEnd = () => {
    const moveItem = exportFields.value[moveIndex.value]
    const targetItem = exportFields.value[targetIndex.value]
    exportFields.value.splice(moveIndex.value, 1, targetItem)
    exportFields.value.splice(targetIndex.value, 1, moveItem)
  }

  // 当拖动的元素进入到当前元素时触发
  const handleDragEnter = (index: number) => {
    targetIndex.value = index
  }

  const { getOptions: getNetworkTypeOptions, options: netWorktypeOptions } =
    useGetNetowrkTypeOptionsService
  /**
   * 获取服务商分类
   */
  const handleGetNetworkTypeOptions = _.throttle((query: string) => {
    getNetworkTypeOptions(query)
  }, 500)
  // 重置事件
  const onReset = () => {
    category.value = null
    type.value = null
    name.value = ''
    teamType.value = null
    networkTypeId.value = null
    getnetworkListRows()
  }
  watch(route, (value) => {
    if (value.name === 'netList') {
      getnetworkListRows()
    }
  })
  onMounted(() => {
    getNetworkTypeOptions('')
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
